package ai.people.platform.archives.service.impl;

import ai.people.core.security.entity.AuthenticationUser;
import ai.people.core.security.support.RequestHolderUtil;
import ai.people.netmon.framework.domain.archives.entity.PersonArchivesTags;
import ai.people.netmon.framework.domain.archives.entity.PersonArchivesTagsAttribute;
import ai.people.netmon.framework.domain.archives.vo.ArchivesTagsVO;
import ai.people.netmon.framework.exception.enums.CommonEnum;
import ai.people.netmon.framework.utils.AssertUtils;
import ai.people.platform.archives.mapper.PersonArchivesTagsMapper;
import ai.people.platform.archives.service.PersonArchivesTagsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toMap;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhenglin
 * @since 2022-04-26
 */
@Service
public class PersonArchivesTagsServiceImpl extends ServiceImpl<PersonArchivesTagsMapper, PersonArchivesTags> implements PersonArchivesTagsService {

    @Autowired
    PersonArchivesTagsMapper mapper;

    @Override
    public List<ArchivesTagsVO> listTags() {
        List<ArchivesTagsVO> result = new ArrayList<>();
        List<PersonArchivesTags> personArchivesTags = mapper.listTags();

        for (PersonArchivesTags personArchivesTag : personArchivesTags) {
            ArchivesTagsVO archivesTagsVO = new ArchivesTagsVO();
            archivesTagsVO.setTagCode(personArchivesTag.getTagCode());
            archivesTagsVO.setTagName(personArchivesTag.getTagName());
            archivesTagsVO.setType(personArchivesTag.getType());
            List<PersonArchivesTagsAttribute> attributes = personArchivesTag.getAttributes();
            Map<String, String> attrs = attributes.stream().collect(toMap(PersonArchivesTagsAttribute::getAttrCode, PersonArchivesTagsAttribute::getAttrName));
            archivesTagsVO.setAttrs(attrs);
            result.add(archivesTagsVO);
        }

        return result;
    }

    @Override
    public void addTag(PersonArchivesTags tag) {
        //获取登录用户ID
        AuthenticationUser loginUser = RequestHolderUtil.loginUser();
        Long userId = loginUser.getUserId();
        tag.setCreatorId(userId);
        boolean save = save(tag);
        AssertUtils.isTrue(save, CommonEnum.FAIL);
    }

}
